const app = getApp()
const offon = true
module.exports = {
  // 创建一个 WebSocket 连接
  connect: function(cb) {
    app.globalData.socket = wx.connectSocket({
      url: app.globalData.Weburl,
      fail(err) {
        console.log(err)
        if (err) {
          console.log('Socket连接失败', 'color:red', err)
          app.globalData.socketConnectFail = true // 定义一个全局变量，当链接失败时改变变量的值
        }
      },
      success() {
        wx.onSocketOpen((res) => {
          console.log('WebSocket打开成功');
          app.globalData.socket.send({
            // 登录
            data: JSON.stringify({
              appid: app.globalData.imID,
              type: 'login',
              uid: wx.getStorageSync('userInfo').openid,
              uid_name: wx.getStorageSync('userInfo').nickname,
              uid_head: wx.getStorageSync('userInfo').src
            }),
            success: res => {
              console.log('用户登录发送成功')
              app.globalData.offon = true
              cb()
            },
            fail: res => {
              console.log("登录失败")
            }
          })
        })
      }
    })
  },
  // 监听WebSocket连接打开事件。
  openWs: function(callback) {
    this.connect(() => {
      // 监听断开
      app.globalData.socket.onClose(res => {
        console.log('断开：正在重新连接...')
        // 关闭重新连接
      })
      if (callback){
        callback()
      }
    })
  },
  send: function(data,cb) {
    app.globalData.socket.send({
      // 登录
      data: JSON.stringify(data),
      success: res => {
        console.log('发送成功')
      },
      fail: err => {
        console.log("发送失败", 'color:red', err)
        if (err.errMsg =='SocketTask.send:fail SocketTask.readState is not OPEN'){
          if(cb){
            cb()
          }
        }
      }
    })
  },
  onMessage: function (callback) {
    app.globalData.socket.onMessage(res => {
      var ress = JSON.parse(res.data)
      console.log(ress)
      callback(ress)
    })
  }
}